package com.googlecode.lookie.platform.image.resource;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class UrlResource
    extends AbstractResource
    implements NamedResource, MimeTypedResource
{

    private URL url;

    private URLConnection connection;

    public UrlResource( URL url )
    {

        this.url = url;
    }

    public String getName()
    {

        return url.getPath();
    }

    public String getMimeType()
        throws ResourceException
    {

        if ( connection == null )
        {
            try
            {
                connection = url.openConnection();
            }
            catch ( IOException e )
            {
                throw new ResourceException( e );
            }
        }

        return connection.getContentType();
    }

    public InputStream createInputStream()
        throws ResourceException
    {

        if ( connection == null )
        {
            try
            {
                connection = url.openConnection();
            }
            catch ( IOException e )
            {
                throw new ResourceException( e );
            }
        }

        try
        {
            return connection.getInputStream();
        }
        catch ( IOException e )
        {
            throw new ResourceException( e );
        }
    }

}
